package jsu.blogger.controller;

import jsu.blogger.pojo.Result;
import jsu.blogger.service.impl.GetUserDataServiceImpl;
import jsu.blogger.service.impl.SystemNoticeService;
import jsu.blogger.service.inter.LiveService;
import jsu.blogger.service.inter.UserFollowService;
import jsu.blogger.util.ReturnResultUtil;
import jsu.blogger.util.UserUtil;
import jsu.blogger.websocket.WebSocketServer;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.util.*;

@RestController()
@RequestMapping("/user")
//用来获取用户相关信息的控制器
public class UserController {
    @Autowired
    private LiveService liveService;
    @Autowired
    private  GetUserDataServiceImpl getUserDataServiceImpl;
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    //获取用户粉丝列表的接口

    @GetMapping("/getUserFollowers/{uid}")
    public Result getUserFollowers(@PathVariable Long uid){
        List<Long> followers=liveService.selectFollowersUid(uid);
        List<Object> result=new ArrayList<>();
        //找到粉丝之后，再确定自己是不是也关注了粉丝
        followers.forEach((follower)->{
            Map<String,Object> map=new HashMap<>();
            map.put("uid",follower);
            map.put("username", getUserDataServiceImpl.getUsernameByUserId(follower));
            map.put("time",liveService.isFollow(follower,uid));
            Timestamp createdAt=liveService.isFollow(uid,follower);
            if(createdAt!=null){
                map.put("isFollow",true);
            }
            File userAvatar=getUserDataServiceImpl.getUserAvatar(follower);
            Map<String,Object> reMap=new HashMap<>();
            if(userAvatar!=null){
                try{
                    String imgType="data:image/"+this.getFileExtension(userAvatar)+";";
                    // 将文件内容读取为字节数组
                    byte[] fileContent = Files.readAllBytes(userAvatar.toPath());
                    // 将字节数组编码为 Base64 字符串
                    String base64String = Base64.getEncoder().encodeToString(fileContent);

                    reMap.put("imgType",imgType);
                    reMap.put("userAvatar",base64String);
                } catch (IOException e) {
                    log.error(String.valueOf(e));
                }
            }
            map.put("avatar",reMap);
            result.add(map);
        });
        return ReturnResultUtil.success(result);
    }
    @Autowired
    private UserFollowService userFollowService;


    @GetMapping("/follow/{follower}/{followed}/{way}")
    public Result follow(@PathVariable Long follower,@PathVariable Long followed,@PathVariable String way){
        //先判断是否已经关注
//        Timestamp time=liveService.isFollow(follower,followed);
//        if(time!=null){
//            return  ReturnResultUtil.failure("关注失败，你之前已经关注了！");
//        }
//
//        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
//
//        if(liveService.followSb(follower,followed,timestamp)){
//            return ReturnResultUtil.success();
//        }else{
//            return  ReturnResultUtil.failure("关注失败！");
//        }
        boolean res=userFollowService.followUser(follower,followed);
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
        if(res){
            SystemNoticeService.noticeFansFollow(follower,followed,getUserDataServiceImpl.getUsernameByUserId(follower),way,timestamp);
        }
        return  res? ReturnResultUtil.success() : ReturnResultUtil.failure("关注失败！");

    }
    @GetMapping("/cancelFollow/{follower}/{followed}")
    public Result cancelFollow(@PathVariable Long follower,@PathVariable Long followed){
        //先判断是否已经关注
//        Timestamp time=liveService.isFollow(follower,followed);
//        if(time==null){
//            return  ReturnResultUtil.failure("取消关注失败，你还没有关注别人");
//        }
//        if(liveService.cancelFollowSb(follower,followed)){
//            return ReturnResultUtil.success();
//        }else{
//            return ReturnResultUtil.failure("取消关注失败");
//        }

        return userFollowService.unfollowUser(follower,followed) ? ReturnResultUtil.success() :  ReturnResultUtil.failure("取消关注失败");
    }
    @GetMapping("/isFollow/{follower}/{followed}")
    public Result isFollow(@PathVariable Long follower, @PathVariable Long followed){
        Timestamp time=liveService.isFollow(follower,followed);
        Timestamp timestamp=liveService.isFollow(followed,follower);
        if(time!=null){
            return  ReturnResultUtil.success(true);
        }else{
            return ReturnResultUtil.success(false);
        }
    // return  ReturnResultUtil.success();
    }
    private String getFileExtension(File file) {
        // 确保传入的是有效的文件对象
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("文件不存在或无效");
        }
        // 获取文件名
        String fileName = file.getName();

        // 找到最后一个点的位置
        int lastDotIndex = fileName.lastIndexOf('.');

        // 如果没有点，返回空字符串
        if (lastDotIndex == -1) {
            return "";
        }
        // 提取后缀名并转换为小写
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }

}
